#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
搜狐号草稿发布器 v3.0 使用示例
演示如何使用新增的素材功能
"""

import os
import sys
from sohu_draft_publisher_v3 import SohuDraftPublisherV3

def example_batch_process_with_materials():
    """示例1: 批量处理markdown文件（带素材插入）"""
    print("=== 示例1: 批量处理markdown文件（带素材插入） ===")
    
    # 配置路径
    source_dir = "/Users/fuzhengliang/Desktop/project-source/workspace-mygitee/zimeiti/星座"
    published_dir = "/Users/fuzhengliang/Desktop/project-source/workspace-mygitee/zimeiti/星座/已发"
    config_file = "sohu_config.json"
    
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisherV3(config_file)
        
        # 批量处理文件
        print(f"开始批量处理目录: {source_dir}")
        report = publisher.process_directory(
            source_dir=source_dir,
            published_dir=published_dir,
            delay=3.0  # 3秒间隔，避免请求过于频繁
        )
        
        # 显示处理结果
        print(f"\n处理完成！")
        print(f"总文件数: {report['total_files']}")
        print(f"成功数量: {report['success_count']}")
        print(f"失败数量: {report['failed_count']}")
        
        # 生成详细报告
        report_file = publisher.generate_report(report)
        print(f"详细报告已保存到: {report_file}")
        
    except Exception as e:
        print(f"批量处理失败: {e}")

def example_single_file_with_material():
    """示例2: 处理单个文件（带素材插入）"""
    print("\n=== 示例2: 处理单个文件（带素材插入） ===")
    
    # 配置路径
    file_path = "/Users/fuzhengliang/Desktop/project-source/workspace-mygitee/zimeiti/星座/测试文章.md"
    published_dir = "/Users/fuzhengliang/Desktop/project-source/workspace-mygitee/zimeiti/星座/已发"
    config_file = "sohu_config.json"
    
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisherV3(config_file)
        
        # 处理单个文件
        print(f"开始处理文件: {file_path}")
        result = publisher.process_single_file(
            file_path=file_path,
            published_dir=published_dir
        )
        
        # 显示处理结果
        if result['success']:
            print("✅ 文件处理成功！")
            print(f"使用素材: {result.get('material_used', 'None')}")
            if result.get('file_moved'):
                print("📁 文件已移动到已发目录")
        else:
            print("❌ 文件处理失败！")
            print(f"错误信息: {result['message']}")
        
    except Exception as e:
        print(f"单文件处理失败: {e}")

def example_test_materials_api():
    """示例3: 测试素材API功能"""
    print("\n=== 示例3: 测试素材API功能 ===")
    
    config_file = "sohu_config.json"
    
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisherV3(config_file)
        
        # 测试获取素材
        print("正在获取素材...")
        materials = publisher.get_materials(page_num=1, page_size=10)
        
        if materials:
            print(f"✅ 成功获取 {len(materials)} 个素材")
            
            # 显示前3个素材信息
            for i, material in enumerate(materials[:3]):
                print(f"\n素材 {i+1}:")
                print(f"  名称: {material.get('name', 'Unknown')}")
                print(f"  ID: {material.get('id', 'Unknown')}")
                print(f"  尺寸: {material.get('content', {}).get('width', 'Unknown')}x{material.get('content', {}).get('height', 'Unknown')}")
                print(f"  URL: {publisher.format_material_url(material.get('content', {}).get('url', ''))}")
            
            # 测试随机选择
            print("\n测试随机选择素材...")
            selected = publisher.select_random_material(materials)
            if selected:
                print(f"✅ 随机选择了素材: {selected.get('name', 'Unknown')}")
            
        else:
            print("❌ 未能获取到素材")
        
    except Exception as e:
        print(f"素材API测试失败: {e}")

def example_custom_content_with_material():
    """示例4: 自定义内容发布（带素材）"""
    print("\n=== 示例4: 自定义内容发布（带素材） ===")
    
    config_file = "sohu_config.json"
    
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisherV3(config_file)
        
        # 自定义内容
        title = "测试文章 - 带随机素材"
        brief = "这是一篇测试文章，用于验证v3.0版本的素材插入功能。"
        content = "<h1>测试文章 - 带随机素材</h1><p>这是文章的正文内容。素材将会插入到标题下方。</p><p>这里是更多的内容...</p>"
        
        # 获取并插入素材
        print("正在获取随机素材...")
        materials = publisher.get_materials()
        selected_material = publisher.select_random_material(materials)
        
        if selected_material:
            print(f"选择了素材: {selected_material.get('name', 'Unknown')}")
            
            # 插入素材到内容
            content_with_material = publisher.insert_material_to_content(content, selected_material)
            
            # 设置封面
            cover_url = publisher.format_material_url(selected_material['content']['url'])
            
            # 保存草稿
            print("正在保存草稿...")
            result = publisher.save_draft(
                title=title,
                brief=brief,
                content=content_with_material,
                cover=cover_url
            )
            
            if result['success']:
                print("✅ 草稿保存成功！")
                print(f"使用封面: {cover_url}")
            else:
                print("❌ 草稿保存失败！")
                print(f"错误信息: {result['message']}")
        else:
            print("❌ 未能获取到素材，使用默认设置保存")
            result = publisher.save_draft(title=title, brief=brief, content=content)
            print(f"保存结果: {'成功' if result['success'] else '失败'}")
        
    except Exception as e:
        print(f"自定义内容发布失败: {e}")

def example_materials_cache_test():
    """示例5: 测试素材缓存功能"""
    print("\n=== 示例5: 测试素材缓存功能 ===")
    
    config_file = "sohu_config.json"
    
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisherV3(config_file)
        
        print("第一次获取素材（从API）...")
        import time
        start_time = time.time()
        materials1 = publisher.get_materials(page_num=1)
        end_time = time.time()
        print(f"耗时: {end_time - start_time:.2f}秒，获取到 {len(materials1)} 个素材")
        
        print("\n第二次获取素材（应该使用缓存）...")
        start_time = time.time()
        materials2 = publisher.get_materials(page_num=1)
        end_time = time.time()
        print(f"耗时: {end_time - start_time:.2f}秒，获取到 {len(materials2)} 个素材")
        
        # 验证缓存是否生效
        if materials1 == materials2:
            print("✅ 缓存功能正常工作")
        else:
            print("❌ 缓存功能可能有问题")
        
    except Exception as e:
        print(f"缓存测试失败: {e}")

def main():
    """主函数"""
    print("搜狐号草稿发布器 v3.0 使用示例")
    print("=" * 50)
    
    # 检查配置文件
    config_file = "sohu_config.json"
    if not os.path.exists(config_file):
        print(f"❌ 配置文件 {config_file} 不存在！")
        print("请先创建配置文件，参考 README.md 中的说明。")
        return
    
    print("请选择要运行的示例:")
    print("1. 批量处理markdown文件（带素材插入）")
    print("2. 处理单个文件（带素材插入）")
    print("3. 测试素材API功能")
    print("4. 自定义内容发布（带素材）")
    print("5. 测试素材缓存功能")
    print("6. 运行所有示例")
    
    try:
        choice = input("\n请输入选择 (1-6): ").strip()
        
        if choice == '1':
            example_batch_process_with_materials()
        elif choice == '2':
            example_single_file_with_material()
        elif choice == '3':
            example_test_materials_api()
        elif choice == '4':
            example_custom_content_with_material()
        elif choice == '5':
            example_materials_cache_test()
        elif choice == '6':
            example_test_materials_api()
            example_materials_cache_test()
            example_custom_content_with_material()
            # 注意：批量处理和单文件处理需要实际的文件，这里跳过
            print("\n注意：批量处理和单文件处理示例需要实际的markdown文件，已跳过。")
        else:
            print("无效的选择！")
    
    except KeyboardInterrupt:
        print("\n\n用户取消操作")
    except Exception as e:
        print(f"\n运行示例时出错: {e}")

if __name__ == '__main__':
    main()